(function(w){

//-------------------------------功能函数begin--------------------------------------------------------
	// 排序函数

	function objKeySort(arys) {
      //先用Object内置类的keys方法获取要排序对象的属性名数组，再利用Array的sort方法进行排序
       var newkey = Object.keys(arys).sort();
       // console.log('newkey=' + newkey);
       var newObj = ''; //创建一个新的对象，用于存放排好序的键值对
       for (var i = 0; i < newkey.length; i++) {
           //遍历newkey数组
           newObj += [newkey[i]] + '=' + arys[newkey[i]] + '&';
       }
    return newObj.substring(0, newObj.length - 1);
  }


// sha1 运算函数
    function add(x, y) {
        return((x & 0x7FFFFFFF) + (y & 0x7FFFFFFF)) ^ (x & 0x80000000) ^ (y & 0x80000000);
    }

    function SHA1hex(num) {
        var sHEXChars = "0123456789abcdef";
        var str = "";
        for(var j = 7; j >= 0; j--)
            str += sHEXChars.charAt((num >> (j * 4)) & 0x0F);
        return str;
    }

    function AlignSHA1(sIn) {
        var nblk = ((sIn.length + 8) >> 6) + 1,
            blks = new Array(nblk * 16);
        for(var i = 0; i < nblk * 16; i++) blks[i] = 0;
        for(i = 0; i < sIn.length; i++)
            blks[i >> 2] |= sIn.charCodeAt(i) << (24 - (i & 3) * 8);
        blks[i >> 2] |= 0x80 << (24 - (i & 3) * 8);
        blks[nblk * 16 - 1] = sIn.length * 8;
        return blks;
    }

    function rol(num, cnt) {
        return(num << cnt) | (num >>> (32 - cnt));
    }

    function ft(t, b, c, d) {
        if(t < 20) return(b & c) | ((~b) & d);
        if(t < 40) return b ^ c ^ d;
        if(t < 60) return(b & c) | (b & d) | (c & d);
        return b ^ c ^ d;
    }

    function kt(t) {
        return(t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
            (t < 60) ? -1894007588 : -899497514;
    }

    function SHA1(sIn) {
        var x = AlignSHA1(sIn);
        var w = new Array(80);
        var a = 1732584193;
        var b = -271733879;
        var c = -1732584194;
        var d = 271733878;
        var e = -1009589776;
        for(var i = 0; i < x.length; i += 16) {
            var olda = a;
            var oldb = b;
            var oldc = c;
            var oldd = d;
            var olde = e;
            for(var j = 0; j < 80; j++) {
                if(j < 16) w[j] = x[i + j];
                else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
                t = add(add(rol(a, 5), ft(j, b, c, d)), add(add(e, w[j]), kt(j)));
                e = d;
                d = c;
                c = rol(b, 30);
                b = a;
                a = t;
            }
            a = add(a, olda);
            b = add(b, oldb);
            c = add(c, oldc);
            d = add(d, oldd);
            e = add(e, olde);
        }
        SHA1Value = SHA1hex(a) + SHA1hex(b) + SHA1hex(c) + SHA1hex(d) + SHA1hex(e);
        return SHA1Value.toUpperCase();
    }

    function SHA2(sIn) {
        return SHA1(sIn).toLowerCase();
    }

    function getQueryVariable(variable) //获取链接后面的参数和值
    {
           var query = window.location.search.substring(1);
           var vars = query.split("&");
           for (var i=0;i<vars.length;i++) {
                   var pair = vars[i].split("=");
                   if(pair[0] == variable){return pair[1];}
           }
           return(false);
    }


//-------------------------------功能函数end--------------------------------------------------------



//-------------------------------业务函数begin--------------------------------------------------------

	const URL = "https://sgb-8gqmg7kv48722f4e-1306391227.ap-shanghai.app.tcloudbase.com/test-dev/ticket"

	function wxSDK(){

		return new Promise((resolve,reject)=>{
			$.get( URL,function (data){
				const o = JSON.parse(data)['ticket']
				resolve(o)
			})

		})
	}

	function login(){ //登录模块

		lsa.get('refresh_token') == null?lsa.set('refresh_token','null'):''

	    if(lsa.get('refresh_token') !== 'null'){

			$.get(URL+'type=refresh_token&refresh_token='+ lsa.get('refresh_token'),function (data){

				 var userInfo = JSON.parse(data)
         console.log('userInfo=>',userInfo)
				 if(userInfo.refresh_token == null){  //如果热刷新失效则进行重新登录

					$("#nickname").text('点击头像登录')

					$("#headimgurl img").attr('src',"https://srrz-2g24l1oea7a7e67e-1304952114.tcloudbaseapp.com/sgb2.0/img/%E5%A4%B4%E5%83%8F.png")

					shouQuan()

					return
				 }
				 $("#nickname").text(userInfo.nickname)
				 $("#headimgurl img").attr('src',userInfo.headimgurl)
				 lsa.set('refresh_token',userInfo.refresh_token)
			})

	    }else{

	    	shouQuan()
	}


	function shouQuan(){

     	var code = getQueryVariable("code");

        if(code){

        	if(lsa.get('code')!==code){

        		lsa.set('code',code)

        		new Promise((resolve,reject)=>{
        			$.get(URL+'type=authorization_code&code='+ code,function (data){
        				resolve(data)
        			})

        		}).then(res=>{

					   var userInfo = JSON.parse(res)

  					 $("#nickname").text(userInfo.nickname)
             $("#headimgurl img").attr('src',userInfo.headimgurl)
             lsa.set('refresh_token',userInfo.refresh_token)
             lsa.set('openid',userInfo.openid)
              console.log('userInfo=>',userInfo)
  					 new Promise((resolve,reject)=>{

  					 	wxCloud.cloud().callFunction({
                 	name:"sgb-login-user-info-add",
                 	data:userInfo,
                 	success:function(res){
                 		console.log("用户信息上传成功=>",res)
                 	},
                 	fail:function(erro){

                 		console.log('用户信息上传失败erro=>',erro)
                 	}
                 })

  					 })

        		})


        	}


        }else{

        	login_url()
	}

	}

	}
	function login_url(){ //登录重定向

			if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {//判断是否是移动设备打开。browser代码在下面

				var ua = navigator.userAgent.toLowerCase();//获取判断用的对象
				if (ua.match(/MicroMessenger/i) == "micromessenger") {
					//在微信中打开
					console.log('在微信内打开')
					var redirect_uri = encodeURI(location.href).replace(/#.+/,"")

					var state = "111"

					var appid = "wx258fd99a593928a8"

					var scope = "snsapi_userinfo"

					var url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid +"&redirect_uri=" + redirect_uri + "&response_type=code&scope=" + scope + "&state=" + state + "#wechat_redirect"

					window.location.href=url

				}
				if (ua.match(/WeiBo/i) == "weibo") {
					//在新浪微博客户端打开
				}
				if (ua.match(/QQ/i) == "qq") {
					//在QQ空间打开
				}
				if (browser.versions.ios) {
					//是否在IOS浏览器打开
					console.log('在IOS内打开')
				}
				if(browser.versions.android){
					//是否在安卓浏览器打开
					console.log('在安卓内打开')
				}
			} else {
				//否则就是PC浏览器打开
				console.log('在PC内打开')
			}


		return

	}

	function SDKyanzheng(jsapi_ticket){ //微信验证
		var nonceStr = 'Wm3WZYTPz0wzccnW'
		var ts = Math.round(new Date().getTime() / 1000).toString()
		var url = window.location.href
    	var string1 = 'jsapi_ticket='+jsapi_ticket+'&noncestr='+nonceStr+'&timestamp='+ts+'&url='+url
    	var data = {
    		jsapi_ticket:jsapi_ticket,
    		noncestr:nonceStr,
    		timestamp:ts,
    		url:url
    	}
    	var signature = SHA1(objKeySort(data))
		return new Promise((resolve,reject)=>{
			wx.config({
				debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
				appId: 'wxb8513069f2775c8d', // 必填，公众号的唯一标识 wxb8513069f2775c8d
				timestamp: ts, // 必填，生成签名的时间戳
				nonceStr: nonceStr, // 必填，生成签名的随机串
				signature: signature,// 必填，签名
				jsApiList: ['updateTimelineShareData','updateAppMessageShareData'], // 必填，需要使用的JS接口列表
				openTagList: ['wx-open-audio'],
			});
            wx.error(function(){
				$.get(URL+'type=jsapi&ht=0',function (data){
					resolve(data)
				})
            })
			resolve(wx)
		})
	}

	function fenxiang(title,link,imgUrl,desc=''){ //设置分享朋友圈和微信朋友功能

		wx.ready(function () {

			wx.updateTimelineShareData({
		        title: title, // 分享标题
		        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		        imgUrl: imgUrl, // 分享图标
		        success: function () {
		          // 设置成功
		        }
		     })

	        wx.updateAppMessageShareData({

	            desc: desc, // 分享描述
	            title: title, // 分享标题
		        link: link, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
		        imgUrl: imgUrl, // 分享图标
	            success: function () {
	              // 设置成功

	            }
	        })

	    })

	}


//-------------------------------业务函数end--------------------------------------------------------


  	w.login = login
  	w.wxSDK = wxSDK

	w.SDKyanzheng = SDKyanzheng

	w.fenxiang = fenxiang





})(window)


